# -*- coding: utf-8 -*-
import json

from datetime import datetime
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.encrypt_util import md5
from zc_core.util.common import parse_timestamp, parse_number
from zc_core.util.order_deadline_filter import OrderItemFilter

from njsc.matcher import match_cat_id, match_supplier_id

order_filter = OrderItemFilter()


def parse_catalog(response):
    if not response.text:
        return None
    cats_json = json.loads(response.text)
    cats_list = cats_json.get("data", {}).get("widgets", {}).get("header", {}).get("category_nav", {}) \
        .get("cat_list", [])
    cats = list()
    for cat in cats_list:
        if not cat == cats_list[12]:
            continue
        cols_one = cat.get("children", {}).get("cols_one", [])
        cols_two = cat.get("children", {}).get("cols_two", [])
        cols_one.extend(cols_two)
        for cat1 in cols_one:
            cats.append(build_catalog(cat1, None))
            cat1_child = cat1.get("children")
            if cat1_child and len(cat1_child) > 0:
                for cat2 in cat1_child:
                    cats.append(build_catalog(cat2, cat2.get("parent_id"), 2))

    return cats


def parse_catalog3(response):
    if not response.text:
        return None
    meta = response.meta
    parent_id = meta.get("parentId")
    cats_json = json.loads(response.text)
    cat3_list = cats_json.get("data", {}).get("screen", {}).get("cat", [])
    cats = list()
    for cat3 in cat3_list:
        cats.append(build_catalog(cat3, parent_id, 3))
    return cats


def build_catalog(cat, parent_id, level=1):
    entity = Catalog()

    entity['catalogId'] = str(cat.get('cat_id'))
    entity['catalogName'] = cat.get('cat_name')
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_sku(response):
    meta = response.meta
    batch_no = meta.get("batchNo")
    sku_json = json.loads(response.text)
    sku_list = sku_json.get("data", {}).get('goodsData')
    skus = list()
    for sku in sku_list:
        entity = Sku()
        entity['batchNo'] = batch_no
        product = sku.get('products')
        if product.get("product_id"):
            entity['skuId'] = product.get("product_id")
            # 平台物料编码
            # entity['materialCode'] = product.get("goods_id")
            supplier = sku.get("seller_info")
            entity['supplierId'] = supplier.get("seller_id")
            entity['supplierName'] = supplier.get("seller_name")
            entity['salePrice'] = parse_number(sku.get('price'))
            entity['catalog3Id'] = sku.get('cat_id')

            skus.append(entity)

    return skus


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')

    js = json.loads(response.text)
    item_data = js.get('data')
    nav_list = item_data.get('breadcrumb')
    product_basic = item_data.get('page_product_basic')
    sku_id = product_basic.get('product_id')
    sku_name = product_basic.get('title')
    material_code = product_basic.get('goods_id')
    brand_id = product_basic.get('brand', {}).get('brand_id')
    brand_name = product_basic.get('brand', {}).get('brand_name')
    sku_img = product_basic.get('image_default_url')
    min_buy = product_basic.get('min_buy')
    supplier = item_data.get('seller_info')
    supplier_id = supplier.get('seller_id')
    supplier_name = supplier.get('seller_name')
    unit = item_data.get("unit")

    item = ItemData()
    item['batchNo'] = batch_no
    item['skuId'] = sku_id
    item['brandId'] = brand_id
    item['brandName'] = brand_name
    item['minBuy'] = min_buy
    item['materialCode'] = material_code
    if nav_list:
        if len(nav_list) > 2 and nav_list[1]:
            item['catalog1Id'] = match_cat_id(nav_list[1].get('link'))
            item['catalog1Name'] = nav_list[1].get('title')
        if len(nav_list) > 3 and nav_list[2]:
            item['catalog2Id'] = match_cat_id(nav_list[2].get('link'))
            item['catalog2Name'] = nav_list[2].get('title')
        if len(nav_list) > 4 and nav_list[3]:
            item['catalog3Id'] = match_cat_id(nav_list[3].get('link'))
            item['catalog3Name'] = nav_list[3].get('title')
        if len(nav_list) > 5 and nav_list[4]:
            item['catalog4Id'] = match_cat_id(nav_list[4].get('link'))
            item['catalog4Name'] = nav_list[4].get('title')
    item['skuImg'] = sku_img
    item['skuName'] = sku_name
    sold_count = item_data.get("sales")
    if sold_count:
        item['soldCount'] = sold_count
    item['supplierId'] = supplier_id
    item['supplierName'] = supplier_name

    if unit:
        item['unit'] = unit

    item['genTime'] = datetime.utcnow()

    return item


def parse_price(response):
    js = json.loads(response.text)
    meta = response.meta
    item = meta.get('item')
    data = js.get('data')
    item['salePrice'] = parse_number(data.get('mktprice'))
    item['originPrice'] = parse_number(data.get('price'))

    return item


def parse_order(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    supplier_id = meta.get('supplierId')
    supplier_name = meta.get('supplierName')
    orders = list()
    data_json = json.loads(response.text)
    order_list = data_json.get('data', {}).get('sellLogList', {}).get('data', [])
    for order in order_list:
        order_time = parse_timestamp(order.get('createtime'))
        # 采集截止
        if order_filter.to_save(order_time):
            order_id = order.get('order_id')
            dept = order.get('name')
            sku_id = order.get('product_id')
            price = parse_number(order.get('price'))
            count = int(order.get('number'))
            amount = price * count
            member_id = order.get('member_id')

            model = OrderItem()
            # order_id会重复
            model['id'] = order_id + "_" + sku_id
            model['orderId'] = order_id
            model["amount"] = amount
            model["batchNo"] = batch_no
            model["deptId"] = md5(dept)
            model["orderDept"] = dept
            model["count"] = count
            model["orderTime"] = order_time
            model["skuId"] = sku_id
            model["supplierId"] = supplier_id
            model["supplierName"] = supplier_name
            model["orderUser"] = member_id
            model["genTime"] = datetime.utcnow()
            orders.append(model)

    return orders


# MRO ---------------------
def parse_mro_sellers(response, include_ids):
    sellers = list()
    root_navs = json.loads(response.text)
    for root_nav in root_navs:
        id = root_nav.get('id')
        if id in include_ids:
            children = root_nav.get('children', [])
            for nav in children:
                parse_supplier(nav, sellers)

    return sellers


def parse_supplier(nav, sellers):
    link = nav.get('link', '')
    if link:
        sp = Supplier()
        sp['id'] = match_supplier_id(link)
        sp['name'] = nav.get('title', '')
        sellers.append(sp)

    children = nav.get('children', [])
    if children:
        for row in children:
            parse_supplier(row, sellers)


def parse_mro_sku(response):
    sku_list = list()
    meta = response.meta
    sp_id = meta.get("spId")
    sp_name = meta.get("spName")
    batch_no = meta.get("batchNo")
    sku_json = json.loads(response.text)
    rows = sku_json.get("data", {}).get('goodsData', [])
    for row in rows:
        sku = Sku()
        sku['batchNo'] = batch_no
        product = row.get('products')
        if product.get("product_id"):
            sku['skuId'] = product.get("product_id")
            sku['supplierSkuId'] = product.get("seller_own_code")

            sku['skuName'] = row.get("name")
            sku['materialCode'] = str(row.get("goods_id"))
            sku['supplierId'] = sp_id
            sku['supplierName'] = sp_name
            sku['salePrice'] = parse_number(row.get('price'))
            sku['costPrice'] = parse_number(row.get('cost'))
            sku['originPrice'] = parse_number(row.get('mktprice'))
            sku['stock'] = row.get('store')
            sku['unit'] = row.get('unit')
            sku['soldCount'] = row.get('buy_count')
            sku['catalog3Id'] = str(row.get('cat_id'))
            sku['minBuy'] = row.get('min_buy')
            sku_list.append(sku)

    return sku_list
